import { _decorator, Component, Node, SpriteAtlas, Prefab, instantiate, Vec3, UITransform, math, Label, Sprite, Button } from 'cc';
import { Igame } from './Igame';
import { pattern } from './pattern';
const { ccclass, property } = _decorator;



@ccclass('game')
export class game extends Component implements Igame {

    @property(Prefab)
    patternPrefab: Prefab

    @property(Node)
    patternArea: Node

    @property(Label)
    targetLabel: Label

    @property(Label)
    timeLabel: Label

    @property(Button)
    restartButton: Button
    //装位置的数组
    positionArr: Vec3[] = []
    //装方块node的数组
    patternNodeArr: Node[] = []
    //游戏关卡
    gameLevel:number = 11
    //游戏目标key
    targetKey:string
    //游戏时间
    gameTime:number = 0
    //游戏是否胜利 0 等待中 1 执行中 2 胜利-游戏结束 3 失败-游戏结束 
    gameStatus:number = 0

    colorMap_ZH: Map<string, string> = new Map([["green", "绿色"], ["red", "红色"], ["yellow", "黄色"]])

    patternMap_ZH: Map<string, string> = new Map([["cirle", "圆形"], ["five", "五边形"], ["love", "爱心"], ["square", "正方形"]])

    patternKeyList: string[] = []
    
    existKeyList: string[] = []
    //游戏运行时加载
    onLoad() {
        //初始化方块
        this.init(this.gameLevel)
    }
    update(dt){
        if(this.gameLevel >= 2 && this.gameStatus == 1){
            this.gameTime += dt
            this.timeLabel.string = "计时器:"+this.gameTime.toFixed(3)
        }

    }
    //随机目标值
    target() {
        let index = this.getRandomNum(0,this.existKeyList.length-1)
        let key = this.existKeyList[index]
        this.targetKey = key
        let keyList = key.split("_")
        this.targetLabel.string = "请点击"+this.colorMap_ZH.get(keyList[0])+"的"+this.patternMap_ZH.get(keyList[1])       
    }
    //初始化方块
    init(level: number) {
        console.log("当前游戏关卡:"+this.gameLevel);
        //初始化位置数组 清空节点的child 清空方块数组 给keylist赋值
        this.restartButton.node.active = false
        this.positionArr = []
        this.patternArea.removeAllChildren()
        this.patternNodeArr = []
        this.existKeyList = []
        this.patternKeyList = ["green_cirle", "green_five", "green_love", "green_square",
        "red_cirle", "red_five", "red_love", "red_square",
        "yellow_cirle", "yellow_five", "yellow_love", "yellow_square"]
        for (let i = 0; i < level; i++) {
            let patternNode = instantiate(this.patternPrefab);
            patternNode.getComponent(pattern).initPattern(this.getRandomKey())
            //给预制体里面的接口赋值
            patternNode.getComponent(pattern).igame = this
            patternNode.setPosition(this.getPosition(this.positionArr))
            let a = patternNode.getComponent(UITransform).width
            this.patternArea.addChild(patternNode)
            this.patternNodeArr.push(patternNode)
        }
        //随机题目
        this.target()
    }
    //随机获取下一个方块的位置
    getPosition(pos: Vec3[]): Vec3 {
        if (pos.length == 0) {
            let position = new Vec3(this.getRandomNum(-270, 270), this.getRandomNum(-500, 400), 0);
            this.positionArr.push(position);
            return position;
        } else {
            let newPosition;
            let flag = true
            while (flag) {
                newPosition = new Vec3(this.getRandomNum(-270, 270), this.getRandomNum(-500, 400), 0);
                //循环遍历，判断新生成的位置是否符合标准
                for (let i = 0; i < this.positionArr.length; i++) {
                    let pos = this.positionArr[i]
                    let distance = Vec3.distance(pos, newPosition)
                    if (distance > 142) {
                        flag = false
                    } else {
                        flag = true
                        break;
                    }
                }
            }
            this.positionArr.push(newPosition);
            return newPosition
        }
    }
    //取区间内随机数
    public getRandomNum(min: number, max: number): number {
        // -500,400 取值就是0到900的随机值加上-500
        return Math.floor(Math.random() * (max - min)) + min
    }
    //获取随机的key
    public getRandomKey():string{
        let index = this.getRandomNum(0,this.patternKeyList.length-1)
        let key = this.patternKeyList[index]
        this.patternKeyList.splice(index,1)
        this.existKeyList.push(key)
        return key;
    }
    //方块点击事件
    click(key: string) {
        if(this.gameLevel == 12 && this.gameStatus != 3){
            this.gameStatus = 2
            console.log("游戏胜利，关卡通关");
            this.targetLabel.string = "游戏胜利，恭喜通关" 
            this.timeLabel.string = "总共耗时:"+this.gameTime.toFixed(3)
            let labelText = this.restartButton.node.getChildByName("Label")
            labelText.getComponent(Label).string = "再来一次"
            this.restartButton.node.active = true
            return;
        }
        if(key == this.targetKey && this.gameStatus != 3){
            this.gameStatus = 1
            this.gameLevel += 1
            this.init(this.gameLevel)
        }else{
            this.gameStatus = 3
            console.log("游戏失败");
            this.gameLevel = 1
            this.timeLabel.string = "游戏结束,计时器清零"
            this.restartButton.node.active = true
        }
    }
    //游戏重新开始
    restartGame(){
        this.gameStatus = 0
        this.timeLabel.string = "计时器:0"
        this.init(1);
    }

}



